package com.software.loginregister.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.google.android.material.imageview.ShapeableImageView;
import com.software.loginregister.R;
import com.software.loginregister.api.UserApi;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.vo.UserDetailVO;
import com.software.loginregister.entity.vo.UserUpdateDTO;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import com.yalantis.ucrop.UCrop;

/**
 * 编辑个人资料页面
 * <p>
 * 功能：
 * 1. 展示用户当前信息
 * 2. 修改用户基本信息（昵称、签名、性别、年龄、手机号、邮箱）
 * 3. 头像预览（更换功能待实现）
 * 4. 数据合法性验证
 * 5. 修改确认提示
 * <p>
 * 数据流：
 * 1. 进入页面加载用户详细信息
 * 2. 用户修改信息后点击保存
 * 3. 验证数据合法性
 * 4. 调用API保存修改
 * 5. 返回上一页并刷新
 * <p>
 * 交互：
 * 1. 返回按钮 - 检查是否有修改，有则提示
 * 2. 保存按钮 - 验证并保存修改
 * 3. 头像点击 - 预留更换功能
 * 4. 输入框 - 支持文本输入
 * 5. 性别选择 - 下拉选择
 *
 * @author 赵鑫
 * @version 1.0
 * @since 2024-11-13
 */

public class EditProfileActivity extends AppCompatActivity {

    private static final String REGEX_PHONE = "^1[3-9]\\d{9}$";
    private static final String REGEX_EMAIL = "^[A-Za-z0-9+_.-]+@(.+)$";
    private ImageView btnBack;
    private TextView btnSave;
    private ShapeableImageView avatarView;
    private EditText editNickname;
    private EditText editSignature;
    private Spinner spinnerGender;
    private EditText editAge;
    private EditText editPhone;
    private EditText editEmail;

    private UserApi userApi;
    private Long userId;
    // 保存当前用户信息，用于比较是否修改
    private UserDetailVO currentUser;
    private ArrayAdapter<CharSequence> adapter;
    private static final int REQUEST_PICK_IMAGE = 1001;
    private static final int REQUEST_CROP_IMAGE = 1002;
    private static final int PERMISSION_REQUEST_CODE = 1003;


    // ... 在类的开头添加新的成员变量
    private Uri tempImageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);

        initViews();
        initData();
        setupListeners();
        // 设置状态栏
        setStatusBar();

    }

    private void setStatusBar() {
        Window window = getWindow();
        // 设置状态栏背景为透明
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        // 设置状态栏文字颜色为深色
        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);

    }

    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        btnSave = findViewById(R.id.btn_save);
        avatarView = findViewById(R.id.avatar);
        editNickname = findViewById(R.id.edit_nickname);
        editSignature = findViewById(R.id.edit_signature);
        spinnerGender = findViewById(R.id.spinner_gender);
        editAge = findViewById(R.id.edit_age);
        editPhone = findViewById(R.id.edit_phone);
        editEmail = findViewById(R.id.edit_email);

        // 设置性别选择器适配器
        adapter = ArrayAdapter.createFromResource(this,
                R.array.gender_options, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerGender.setAdapter(adapter);
    }

    private void initData() {
        userApi = RetrofitClient.getInstance().create(UserApi.class);
        /*从SharedPreferences获取用户ID*/
        userId = SharedPreferencesUtil.getUserId(this);
        if (userId == null) {
            Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        /* 加载用户详细信息*/
        loadUserInfo();
    }

    private void loadUserInfo() {
        showLoading();
        userApi.getDetailInfo(userId).enqueue(new Callback<Result<UserDetailVO>>() {
            @Override
            public void onResponse(Call<Result<UserDetailVO>> call, Response<Result<UserDetailVO>> response) {
                hideLoading();
                if (response.isSuccessful() && response.body() != null) {
                    Result<UserDetailVO> result = response.body();
                    if (result.getCode() == 1) {
                        currentUser = result.getData();
                        updateUi(currentUser);
                    } else {
                        Toast.makeText(EditProfileActivity.this,
                                result.getMsg(), Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            }

            @Override
            public void onFailure(Call<Result<UserDetailVO>> call, Throwable t) {
                hideLoading();
                Toast.makeText(EditProfileActivity.this,
                        "网络错误", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    private void updateUi(UserDetailVO user) {
        if (user == null) {
            Toast.makeText(this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 设置昵称
        editNickname.setText(user.getNickname() != null ? user.getNickname() : "");

        // 设置签名
        editSignature.setText(user.getSignature() != null ? user.getSignature() : "");
        // 设置性别 - 根据后端返回值设置正确的选项
        int genderPosition = 0; // 默认"未设置"
        if (user.getGender() != null) {
            switch (user.getGender()) {
                case -1: // 未设置
                    genderPosition = 0;
                    break;
                case 0: // 男
                    genderPosition = 1;
                    break;
                case 1: // 女
                    genderPosition = 2;
                    break;
            }
        }
        spinnerGender.setSelection(genderPosition);

        // 设置年龄 - 添加空值检查
        if (user.getAge() != null) {
            editAge.setText(String.valueOf(user.getAge()));
        } else {
            editAge.setText("0"); // 设置默认值
        }

        // 设置手机号
        editPhone.setText(user.getPhone() != null ? user.getPhone() : "");

        // 设置邮箱
        editEmail.setText(user.getEmail() != null ? user.getEmail() : "");

        // 加载头像
        if (!TextUtils.isEmpty(user.getAvatar())) {
            Glide.with(this)
                    .load(user.getAvatar())
                    .placeholder(R.drawable.ic_defalut_avater)
                    .error(R.drawable.ic_defalut_avater)
                    .into(avatarView);
        }
    }

    private void setupListeners() {
        /*返回按钮*/
        btnBack.setOnClickListener(v -> {
            if (hasChanges()) {
                showDiscardDialog();
            } else {
                finish();
            }
        });

        /*保存按钮*/
        btnSave.setOnClickListener(v -> saveUserInfo());

        /* 头像点击*/
        avatarView.setOnClickListener(v -> showImagePickerDialog());
    }

    private void showImagePickerDialog() {
        String[] options = {"拍照", "从相册选择"};
        new AlertDialog.Builder(this)
                .setTitle("选择图片来源")
                .setItems(options, (dialog, which) -> {
                    if (which == 0) {
                        checkCameraPermission();
                    } else {
                        checkGalleryPermission();
                    }
                })
                .show();
    }

    private void checkCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    PERMISSION_REQUEST_CODE);
        } else {
            openCamera();
        }
    }

    private void checkGalleryPermission() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            // Android 10及以上使用新的权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_MEDIA_IMAGES},
                        PERMISSION_REQUEST_CODE);
            } else {
                openGallery();
            }
        }
    }

    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        tempImageUri = createTempImageUri();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tempImageUri);
        startActivityForResult(intent, REQUEST_PICK_IMAGE);
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_PICK_IMAGE);
    }

    private Uri createTempImageUri() {
        File tempFile = new File(getExternalCacheDir(), "temp_image.jpg");
        return FileProvider.getUriForFile(this,
                "com.software.loginregister.provider",  // 确保这里的包名与你的应用包名一致
                tempFile);
    }

    // 在onActivityResult中也添加日志
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("EditProfile", "onActivityResult - requestCode: " + requestCode + ", resultCode: " + resultCode);

        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_PICK_IMAGE) {
                Uri sourceUri = null;
                if (data != null && data.getData() != null) {
                    sourceUri = data.getData();
                } else if (tempImageUri != null) {
                    sourceUri = tempImageUri;
                }

                Log.d("EditProfile", "获取到图片Uri: " + sourceUri);
                if (sourceUri != null) {
                    try {
                        // 确保Uri可读
                        getContentResolver().takePersistableUriPermission(sourceUri,
                                Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    } catch (SecurityException e) {
                        Log.e("EditProfile", "无法获取Uri权限", e);
                    }
                    startCrop(sourceUri);
                } else {
                    Log.e("EditProfile", "sourceUri为空");
                    Toast.makeText(this, "无法获取图片", Toast.LENGTH_SHORT).show();
                }
            } else if (requestCode == UCrop.REQUEST_CROP) {
                final Uri resultUri = UCrop.getOutput(data);
                Log.d("EditProfile", "裁剪完成，结果Uri: " + resultUri);
                if (resultUri != null) {
                    uploadImage(resultUri);
                } else {
                    Log.e("EditProfile", "裁剪结果Uri为空");
                }
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            final Throwable cropError = UCrop.getError(data);
            Log.e("EditProfile", "裁剪失败", cropError);
            if (cropError != null) {
                Toast.makeText(this, "裁剪失败: " + cropError.getMessage(), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "裁剪失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void startCrop(Uri sourceUri) {
        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), "cropped_image.jpg"));

        UCrop.Options options = new UCrop.Options();
        options.setCompressionQuality(80);
        options.setToolbarColor(getResources().getColor(R.color.white)); // 使用你的主题颜色
        options.setStatusBarColor(getResources().getColor(R.color.white));
        options.setToolbarTitle("裁剪头像");
        options.setCircleDimmedLayer(true);

        UCrop.of(sourceUri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(500, 500)
                .withOptions(options)
                .start(this, UCrop.REQUEST_CROP);  // 使用 UCrop.REQUEST_CROP 作为请求码
    }

    private void uploadImage(Uri imageUri) {
        Log.d("EditProfile", "开始上传图片，imageUri: " + imageUri);
        showLoading();
        try {
            // 检查输入Uri是否有效
            if (imageUri == null) {
                Log.d("EditProfile", "imageUri为空");
                Toast.makeText(this, "图片数据无效", Toast.LENGTH_SHORT).show();
                hideLoading();
                return;
            }

            // 创建临时文件
            File imageFile = new File(getCacheDir(), "upload_image.jpg");
            Log.d("EditProfile", "临时文件路径: " + imageFile.getAbsolutePath());

            // 复制文件
            copyUriToFile(imageUri, imageFile);
            Log.d("EditProfile", "文件复制完成，文件大小: " + imageFile.length() + " bytes");

            // 创建文件的RequestBody
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), imageFile);
            MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", imageFile.getName(), requestFile);
            RequestBody userIdPart = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(userId));

            Log.d("EditProfile", "开始网络请求，userId: " + userId);
            userApi.uploadAvatar(filePart, userIdPart).enqueue(new Callback<Result<String>>() {
                @Override
                public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                    hideLoading();
                    Log.d("EditProfile", "收到服务器响应，状态码: " + response.code());

                    if (response.isSuccessful() && response.body() != null) {
                        Result<String> result = response.body();
                        Log.d("EditProfile", "服务器返回结果: code=" + result.getCode() + ", msg=" + result.getMsg());

                        // 修改这里的判断逻辑
                        if (result.getCode() == 1) {  // 只判断code是否为1
                            String avatarUrl = result.getMsg(); // 从msg中获取URL
                            currentUser.setAvatar(avatarUrl);
                            Log.d("EditProfile", "头像URL更新成功: " + avatarUrl);

                            // 更新头像显示
                            Glide.with(EditProfileActivity.this)
                                    .load(avatarUrl)
                                    .placeholder(R.drawable.ic_defalut_avater)
                                    .error(R.drawable.ic_defalut_avater)
                                    .into(avatarView);
                            Toast.makeText(EditProfileActivity.this, "头像更新成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("EditProfile", "服务器返回错误: " + result.getMsg());
                            Toast.makeText(EditProfileActivity.this,
                                    result.getMsg() != null ? result.getMsg() : "上传失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Log.e("EditProfile", "服务器响应失败: " + response.message());
                        Toast.makeText(EditProfileActivity.this, "服务器响应失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Result<String>> call, Throwable t) {
                    hideLoading();
                    Log.e("EditProfile", "网络请求失败", t);
                    Toast.makeText(EditProfileActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            Log.e("EditProfile", "处理图片过程中出错", e);
            hideLoading();
            Toast.makeText(this, "处理图片失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    // 新增方法：将Uri复制到文件
    private void copyUriToFile(Uri uri, File destFile) throws IOException {
        Log.d("EditProfile", "开始复制文件，源Uri: " + uri);
        Log.d("EditProfile", "目标文件: " + destFile.getAbsolutePath());

        try (InputStream inputStream = getContentResolver().openInputStream(uri)) {
            if (inputStream == null) {
                Log.e("EditProfile", "无法打开输入流");
                throw new IOException("Failed to open input stream");
            }

            try (OutputStream outputStream = new FileOutputStream(destFile)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                long totalBytes = 0;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                    totalBytes += bytesRead;
                }

                outputStream.flush();
                Log.d("EditProfile", "文件复制完成，总字节数: " + totalBytes);
            }
        } catch (IOException e) {
            Log.e("EditProfile", "复制文件失败", e);
            throw e;
        }
    }

    private boolean hasChanges() {
        if (currentUser == null) {
            return false;
        }

        String currentAge = editAge.getText().toString().trim();
        Integer userAge = currentUser.getAge();

        return !Objects.equals(currentUser.getNickname(), editNickname.getText().toString().trim()) ||
                !Objects.equals(currentUser.getSignature(), editSignature.getText().toString().trim()) ||
                !Objects.equals(currentUser.getGender(), spinnerGender.getSelectedItemPosition()) ||
                !Objects.equals(userAge != null ? String.valueOf(userAge) : "0", currentAge) ||
                !Objects.equals(currentUser.getPhone(), editPhone.getText().toString().trim()) ||
                !Objects.equals(currentUser.getEmail(), editEmail.getText().toString().trim());
    }

    private void showDiscardDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("确定要放弃修改吗？")
                .setPositiveButton("确定", (dialog, which) -> finish())
                .setNegativeButton("取消", null)
                .show();
    }

    private void saveUserInfo() {

        /*数据验证*/
        String nickname = editNickname.getText().toString().trim();
        if (TextUtils.isEmpty(nickname)) {
            Toast.makeText(this, "昵称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 手机号验证
        String phone = editPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!phone.matches(REGEX_PHONE)) {
            Toast.makeText(this, "手机号格式不正确", Toast.LENGTH_SHORT).show();
            return;
        }

        // 邮箱验证
        String email = editEmail.getText().toString().trim();
        if (!TextUtils.isEmpty(email) && !email.matches(REGEX_EMAIL)) {
            Toast.makeText(this, "邮箱格式不正确", Toast.LENGTH_SHORT).show();
            return;
        }

        /*构建更新数据*/
        UserUpdateDTO updateDTO = new UserUpdateDTO();
        updateDTO.setUserId(userId);
        updateDTO.setNickname(nickname);
        updateDTO.setSignature(editSignature.getText().toString().trim());
        updateDTO.setGender(spinnerGender.getSelectedItemPosition());

        // 转换性别值为后端需要的格式
        int selectedPosition = spinnerGender.getSelectedItemPosition();
        int genderValue;
        switch (selectedPosition) {
            case 0: // 未设置
                genderValue = -1;
                break;
            case 1: // 男
                genderValue = 0;
                break;
            case 2: // 女
                genderValue = 1;
                break;
            default:
                genderValue = -1;
        }
        updateDTO.setGender(genderValue);
        try {
            updateDTO.setAge(Integer.parseInt(editAge.getText().toString().trim()));
        } catch (NumberFormatException e) {
            updateDTO.setAge(0);
        }
        updateDTO.setPhone(phone);
        updateDTO.setEmail(email);

        /*调用API保存*/
        showLoading();
        userApi.updateUserInfo(updateDTO).enqueue(new Callback<Result<Boolean>>() {
            @Override
            public void onResponse(Call<Result<Boolean>> call, Response<Result<Boolean>> response) {
                hideLoading();
                if (response.isSuccessful() && response.body() != null) {
                    Result<Boolean> result = response.body();
                    if (result.getCode() == 1) {
                        Toast.makeText(EditProfileActivity.this,
                                "保存成功", Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        Toast.makeText(EditProfileActivity.this,
                                result.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<Result<Boolean>> call, Throwable t) {
                hideLoading();
                Toast.makeText(EditProfileActivity.this,
                        "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /*
    加载对话框
     */
    private ProgressDialog progressDialog;

    private void showLoading() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("加载中...");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }

    private void hideLoading() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onBackPressed() {
        if (hasChanges()) {
            showDiscardDialog();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideLoading();
    }
}